import pygame
import copy
import logging
from conf import *

logger = logging.getLogger(__name__)
logger.setLevel(LOGGING_LEVEL)
logging.basicConfig(format='%(name)s:%(levelname)s:%(message)s')

class SceneObject(pygame.sprite.Sprite):
    def __init__(self, scene, position=[0,0], direction_vector=[0.0,0.0], speed=0.0, image_path=''):
        super().__init__()
        self.scene = scene
        self.image_bank = [] # sprite images
        self.current_image_number = 0
        self.blood = 100.0
        self.attack_power = 0.2
        self.is_alive = True

        self.sound_cnt = SOUND_DELAY

        self.rect = pygame.Rect([ 0,0,1,1 ]) # dummy rect

        if not image_path == '':
            picture = pygame.image.load(image_path)
            picture.convert_alpha()
            self.image_bank.append(picture)

            self.image = self.image_bank[self.current_image_number]
            self.rect = self.image.get_rect()

        # after self.rect object is built
        self.position = position
        self.direction_vector = direction_vector


        self.speed = speed

    @property
    def position(self):
        return self.rect.topleft

    @position.setter
    def position(self, position):
        self.rect.topleft = position

    def load_images(self, image_number, path_format_str):
        self.image_bank.clear()
        for i in range(image_number):
            picture = pygame.image.load(path_format_str.format(i+1))
            picture.convert_alpha()
            self.image_bank.append(picture)

        self.current_image_number = 0
        self.image = self.image_bank[self.current_image_number]
        self.rect = self.image.get_rect()


    def update(self) :
        super().update()
        self.current_image_number = (self.current_image_number + 1 ) % len(self.image_bank)
        self.image = self.image_bank[self.current_image_number]

        self.sound_cnt -= 1

        x, y = self.position
        self.position = [int(x + self.direction_vector[0] * self.speed),
                         int(y + self.direction_vector[1] * self.speed) ]

    def kill_out_of_sight(self):
        # kill the bullet when they run out of the scene
        if not self.scene.rect.contains(self.rect):
            self.kill()

    def draw(self):
        self.scene.screen.blit(self.image, self.position)

    def hit(self, objects):
        logger.debug('hit! Blood=%f' % (self.blood))
        logger.debug(self)
        # Sound
        self.scene.sound_hit.play()
        if isinstance(objects, list):
            for e in objects:
                self.blood -= e.attack_power
        else:
            self.blood -= objects.attack_power

        if self.blood < 0.0:
            self.is_alive = False
        pass

    def clone(self):
        return copy.copy(self)
